﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace Easy_Split
{
    public partial class Form1 : Form
    {
        # region declare variables
        double amount;
        int n;
        double share;
        double mithunval;
        double venkatval;
        double balajival;
        double venkyval;
        double mithuntrans;
        double venkattrans;
        double balajitrans;
        double venkytrans;
        string Paidby;
        string txt_path = "C:\\temp\\easysplit.txt";
        string balance_path = "C:\\temp\\balances.txt";
        int startcount = 0;
        string filter = "Text files|*.txt|All files|*.*";
        string ReportName;
        #endregion

        #region Form related
        #region Form Load
        public Form1()
        {
            InitializeComponent();

            n = 0;
            //Disable the below function to start the application without the read function
            //ReadExcelData(excel_file); //Reading data from Excel File when the application is opened
            ReadTxtData(dataGridView1, txt_path);
            ReadTxtData(dataGridView2, balance_path);

            startcount = (dataGridView1.Rows.Count - 1);
            venkyval = Convert.ToDouble((dataGridView2.Rows[0].Cells[0].Value));
            mithunval = Convert.ToDouble((dataGridView2.Rows[0].Cells[1].Value));
            balajival = Convert.ToDouble((dataGridView2.Rows[0].Cells[2].Value));
            venkatval = Convert.ToDouble((dataGridView2.Rows[0].Cells[3].Value));
            check_color();
            dataGridView2.CurrentCell = null;
            //Status Bar Initialization
            textBox1.Text = ("#Transactions: " + Convert.ToString(dataGridView1.Rows.Count - 1));
            if (File.Exists(txt_path))
            {
                textBox2.Text = ("Last Entry: :" + Convert.ToString(dataGridView1.Rows[(dataGridView1.Rows.Count - 2)].Cells[0].Value));
            }
            else
            {
                textBox2.Text = ("Last Entry: Yet to be entered");
            }
        }
        #endregion
        #region Form Closing
        private void Form1_Load(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show("Thank you for using Easy Split \n Created by Venkitachalam Parameswaran");
        }
        #endregion
        #endregion

        #region Add Button
        private void Submit_Click(object sender, EventArgs e)
        {

            if (Amount.Text != "" && ItemName.Text != "")
            {
                amount = Convert.ToDouble(Amount.Text);

                //Initializing values for every transaction
                share = 0.0;
                venkytrans = 0.0;
                mithuntrans = 0.0;
                balajitrans = 0.0;
                venkattrans = 0.0;

                #region NumberOfPeople

                if (Mithun.Checked && Venkat.Checked && Balaji.Checked && Venky.Checked)
                {
                    n = 4;
                }
                else if ((Mithun.Checked && Venkat.Checked && Balaji.Checked) || (Mithun.Checked && Venkat.Checked && Venky.Checked) || (Mithun.Checked && Balaji.Checked && Venky.Checked) || (Venkat.Checked && Balaji.Checked && Venky.Checked))
                {
                    n = 3;
                }
                else if ((Mithun.Checked && Venkat.Checked) || (Venkat.Checked && Balaji.Checked) || (Balaji.Checked && Venky.Checked) || (Venky.Checked && Mithun.Checked) || (Balaji.Checked && Mithun.Checked) || (Venky.Checked && Venkat.Checked))
                {
                    n = 2;
                }
                else
                {
                    n = 1;
                }
                #endregion

                share = (Math.Round(amount / n, 2));


                #region Adding Share

                if (Mithun.Checked)
                {
                    mithuntrans = share;
                    mithunval += share;
                    Mithun.Checked = false;
                }
                if (Venkat.Checked)
                {
                    venkattrans = share;
                    venkatval += share;
                    Venkat.Checked = false;
                }
                if (Balaji.Checked)
                {
                    balajitrans = share;
                    balajival += share;
                    Balaji.Checked = false;
                }
                if (Venky.Checked)
                {
                    venkytrans = share;
                    venkyval += share;
                    Venky.Checked = false;
                }
                #endregion

                #region RadioButton
                if (radioButton1.Checked)
                {
                    Paidby = Mithun.Text;
                    mithunval -= amount;
                }
                if (radioButton2.Checked)
                {
                    Paidby = Venkat.Text;
                    venkatval -= amount;
                }
                if (radioButton3.Checked)
                {
                    Paidby = Balaji.Text;
                    balajival -= amount;
                }
                if (radioButton4.Checked)
                {
                    Paidby = Venky.Text;
                    venkyval -= amount;
                }
                #endregion
                
                Amount.Clear();
                this.dataGridView1.Rows.Add(System.DateTime.Now.ToString("dd/MM/yyyy"), ItemName.Text, venkytrans, mithuntrans, venkattrans, balajitrans, Paidby);
                //Current Debt
                this.dataGridView2.Rows.Clear();
                this.dataGridView2.Rows.Add(venkyval, mithunval, balajival, venkatval);

                check_color();
                dataGridView2.CurrentCell = null;           
                ItemName.Clear();
                textBox1.Text = ("#Transactions: " + Convert.ToString(dataGridView1.Rows.Count - 1));
                textBox2.Text = ("Last Entry: :" + Convert.ToString(dataGridView1.Rows[(dataGridView1.Rows.Count - 2)].Cells[0].Value));
                export_datagridview_to_txt(dataGridView1, txt_path);
                export_datagridview_to_txt(dataGridView2, balance_path);

                if (Mithun.Checked && Balaji.Checked && Venkat.Checked && Venky.Checked == false)
                {
                    MessageBox.Show("Please Check the people involved in the transaction");
                    
                }
                if (radioButton1.Checked && radioButton2.Checked && radioButton3.Checked && radioButton4.Checked == false)
                {
                    MessageBox.Show("Please indicate the person paid");
                }

            }
            else
            {
                MessageBox.Show("Item Name or Amount cannot be blank");
            }
            if (Mithun.Checked && Balaji.Checked && Venkat.Checked && Venky.Checked == false)
            {
                MessageBox.Show("Please Check the people involved in the transaction");
            }
            if (radioButton1.Checked && radioButton1.Checked && radioButton1.Checked && radioButton1.Checked == false)
            {
                MessageBox.Show("Please indicate the person paid");
            }

        }
        #endregion

        
        #region Writing External Text File
        //Export to Excel
        public void export_datagridview_to_txt(System.Windows.Forms.DataGridView dgv, string txt_file)
        {
            int cols;
            StreamWriter wr = new StreamWriter(txt_file);


            cols = dgv.Columns.Count;

            //write rows to excel file
            for (int i = 0; i < (dgv.Rows.Count - 1); i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    if (dgv.Rows[i].Cells[j].Value != null)
                        wr.Write(dgv.Rows[i].Cells[j].Value + "\t");
                    else
                    {
                        wr.Write("\t");
                    }
                }
                wr.WriteLine();
            }

            //close file
            wr.Close();
        }
        #endregion
          
        #region Reading External Text File
        private void ReadTxtData(System.Windows.Forms.DataGridView dgv, string sFilePath)
        {
            try
            {
                using (StreamReader sr = new StreamReader(sFilePath))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        int rowIndex = dgv.Rows.Add();
                        string[] tokens = line.Split('\t');
                        for (int cnt = 0; cnt < tokens.Length - 1; cnt++)
                        {
                            dgv.Rows[rowIndex].Cells[cnt].Value = tokens[cnt];
                        }

                    }
                }
            }
            catch (Exception e)
            {

            }
            finally
            {
            }
        }
        #endregion

        #region Report
        #region Report Generation
        public void report_datagridview_to_txt(System.Windows.Forms.DataGridView dgv, string condition)
        {
            int cols;

            SaveFileDialog save = new SaveFileDialog();
            save.Filter = filter;
            save.Title = "Save the file";
            if (save.ShowDialog(this) == DialogResult.OK)
            {
                ReportName = save.FileName;
            }
            else
            {
                return;
            }

            StreamWriter wr = new StreamWriter(ReportName);
            cols = dgv.Columns.Count;
            wr.WriteLine("Report Created on \t" + Convert.ToString(System.DateTime.Now + "\r\n"));
            //write rows to excel file
            if (condition == "yes")
            {
                for (int i = 0; i < (dgv.Rows.Count - 1); i++)
                {
                    for (int j = 0; j < cols; j++)
                    {
                        if (dgv.Rows[i].Cells[j].Value != null)
                            wr.Write(dgv.Rows[i].Cells[j].Value + "\t");
                        else
                        {
                            wr.Write("\t");
                        }
                    }
                    wr.WriteLine();
                }
                wr.WriteLine("\r\nBalances: \r\nVenky\t:" + venkyval + "\r\nMithun\t:" + mithunval + "\r\nVenkat\t:" + venkatval + "\r\nBalaji\t:" + balajival);
                //close file
                wr.Close();
            }
            else
            {
                
                {
                     for (int i = 0; i < (dgv.Rows.Count - 1); i++)
                     {
                         for (int j = 0; j < cols; j++)
                         {
                             string today_date = System.DateTime.Now.ToString("dd/MM/yyyy");
                             string cell_value = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
                             if (cell_value == today_date && dgv.Rows[i].Cells[j].Value != null)
                             {
                                  wr.Write(dgv.Rows[i].Cells[j].Value + "\t");
                             }
                             else
                             {
                                  wr.Write("\t");
                             }
                             }
                             wr.WriteLine();
                         }
                     
                    wr.WriteLine("\r\nBalances: \r\nVenky\t:" + venkyval + "\r\nMithun\t:" + mithunval + "\r\nVenkat\t:" + venkatval + "\r\nBalaji\t:" + balajival);
                    //close file
                    wr.Close();
                }
            }
        }
        #endregion
        #region Report Button
        private void Report_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Do you want a report of all transactions?\r\n (Yes= Full transaction history) \r\n (No = Session's Transactions)", "Report Generation", MessageBoxButtons.YesNoCancel);
            if (dr == DialogResult.Yes)
            {
                report_datagridview_to_txt(dataGridView1, "yes");

            }

            else if (dr == DialogResult.No)
            {
                report_datagridview_to_txt(dataGridView1, "No");

            }
            else if (dr == DialogResult.Cancel)
            {
                return;
            }

        }
        #endregion
        #endregion

        #region Search
        #region Search button
        private void search_button_Click(object sender, EventArgs e)
        {
            if (Search_ByName.Checked == true)
            {
                search_method(textBox4.Text, 1);
                Search_ByName.Checked = false;
            }
            else
            {
                string theDate = dateTimePicker1.Value.ToString("dd/MM/yyyy");
                search_method(theDate, 0);
                Search_ByDate.Checked = false;
            }
        }
        #endregion
        #region Search Algorithm
        private void search_method(string criteria1, int column_number)
        {
            textBox3.Text = "ItemName \tVenky \tMithun \tVenkat \tBalaji \tPaidby \r\n\n";
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                    //string cell_value = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
                   
                   if (criteria1 == Convert.ToString(dataGridView1.Rows[i].Cells[column_number].Value))
                    {
                     textBox3.AppendText(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value)
                        +"\t"+"\t" +Convert.ToString(dataGridView1.Rows[i].Cells[2].Value)
                        +"\t" +Convert.ToString(dataGridView1.Rows[i].Cells[3].Value)
                        +"\t" +Convert.ToString(dataGridView1.Rows[i].Cells[4].Value)
                        +"\t" +Convert.ToString(dataGridView1.Rows[i].Cells[5].Value)
                        +"\t" +Convert.ToString(dataGridView1.Rows[i].Cells[6].Value)
                        +"\r\n");
                    
                    }
                else
                {
                   
                }
            }
        
            MessageBox.Show(textBox3.Text);

        }
        #endregion
        #region Search RadioButtons
        private void Search_ByName_Click(object sender, EventArgs e)
        {
            if (Search_ByName.Checked == true)
            {
                textBox4.Visible = true;
                search_button.Visible = true;
            }
            else
            {
                textBox4.Visible = false;
                search_button.Visible = false;
            }
        }
        private void Search_ByDate_Click(object sender, EventArgs e)
        {
            if (Search_ByDate.Checked == true)
            {
                dateTimePicker1.Visible = true;
                search_button.Visible = true;
            }
            else
            {
                dateTimePicker1.Visible = false;
                search_button.Visible = false;
            }
        }
        #endregion
        #endregion

        #region Colors
        private void check_color()
        {
            if (venkyval < 0)
            {
                credit_color(0);
            }
            else
            {
                debit_color(0);
            }
            if (mithunval < 0)
            {
                credit_color(1);
            }
            else
            {
                debit_color(1);
            }
            if (balajival < 0)
            {
                credit_color(2);
            }
            else
            {
                debit_color(2);
            }
            if (venkatval < 0)
            {
                credit_color(3);
            }
            else
            {
                debit_color(3);
            }
        }

        private void credit_color(int column_number)
        {
               dataGridView2.Rows[0].Cells[column_number].Style.BackColor = Color.Green;
        }
        private void debit_color(int column_number)
        {
            dataGridView2.Rows[0].Cells[column_number].Style.BackColor = Color.Magenta;
        }
        #endregion

           

    }
    }
